import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store";
import { userMenus } from "@/api/user";
import { listToTree } from "@/utils/treeUtil";

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login/LoginView.vue')
  },
  {
    path: '/index',
    name: 'index',
    redirect: "/home",
    component: () => import('@/views/layout/indexView.vue'),
    children: []
  }
]

const router = new VueRouter({
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  var path = to.path

  let token = sessionStorage.getItem('token')

  // 如果没有 token 且目标路径不是登录页，则跳转到登录页
  if (!token && to.path !== '/login') {
    next('/login')
  }

  // 如果有 token 且目标路径是登录页，则跳转到主页
  if (token && to.path === '/login') {
    next("/home")
  }

  if (token) {
    if (store.state.menuList.length === 0) {
      // 发生请求获取用户的菜单
      try {
        let { data } = await userMenus()
        if (data && Array.isArray(data.menu)) {
          let dbMenu = listToTree(data.menu)
          let menu = [
            {
              title: '首页',
              icon: 'el-icon-s-home',
              path: "/home"
            },
            ...dbMenu
          ]
          store.commit('initMenu', menu)

          // 动态路由过滤权限
          let menuRouter = data.menu
              .filter(permission => permission.isMenu == 1)
              .map(permission => {
                return {
                  path: permission.path,
                  component: () => import(`@/views/${permission.model}/${permission.component}`)
                }
              })

          let lastRouter = [
            {
              path: '/home',
              name: 'home',
              component: () => import('@/views/home/HomeView.vue')
            },
            ...menuRouter,
            {
              path: '/**',
              name: 'page404',
              component: () => import('@/views/404/404View.vue')
            }
          ]
          lastRouter.forEach(rt => {
            router.addRoute("index", rt)
          })
          next(path)
        } else {
          console.error('userMenus response data.menu is not an array or is undefined')
          next('/login')
        }
      } catch (error) {
        console.error('Failed to fetch user menus:', error)
        next('/login')
      }
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
